package cate.game.util.api;

import cate.common.game.invite.CateInviteEvent;
import cate.game.GameBody;
import cate.game.role.Role;
import cp.solution.business.world.invite.dto.InviteEvent;
import cp.solution.business.world.role.ActiveRoleEntity;
import cp.solution.define.LogcatTag;
import cp.solution.rpc.path.RpcSharePath;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;


@Slf4j
public class WorldApi {

    public static void updateActiveRole(GameBody game, Role role) {
        if(role == null || role.getGame() == null) {
            return;
        }
        if(!role.getGame().isRunning()) {
            return;
        }
        try {
            ActiveRoleEntity ar = new ActiveRoleEntity();
            ar.setRoleId(role.getUid());
            ar.setOpenId(role.getBase().openId);
            ar.setGameId(role.getBase().gameId);
            ar.setSrvId(role.getBase().srvId);
            ar.setRoleName(role.getBase().name);
            ar.setRoleLevel(role.getBase().level);
            ar.setRoleVip(role.getBase().vip);
            ar.setLoginTime(new Date(game.time.now()));
            game.rpcSend().fireAndForgetWorld(RpcSharePath.ROLE_UPDATE_ACTIVE_G2W, ar);
        } catch (Exception e) {
            log.error("向WorldServer role.updateActive 出错", e);
        }
    }

    private static CateInviteEvent createInviteEvent(byte eventType, Role invitee, String inviterRoleId) {
        CateInviteEvent e = new CateInviteEvent();
        e.type = eventType;
        e.inviteeId = invitee.getUid();
        e.inviteeName = invitee.getBase().name;
        e.inviteeLevel = invitee.getBase().level;
        e.inviteeSrvId = invitee.getBase().srvId;
        e.inviterId = inviterRoleId;
        e.inviteePaySum = invitee.getPay().paySum;
        e.invitee = invitee.toAbstract();
        return e;
    }

    private static void dispatchInviteEvent(GameBody game, CateInviteEvent event) {
        try {
            game.rpcSend().fireAndForgetWorld(RpcSharePath.INVITE_EVENT_G2W, event);
            game.logcat().log(LogcatTag.INVITE, "已发送邀请事件:"+event);
        } catch (Exception e) {
            game.logcat().log(LogcatTag.INVITE,
                    "向WorldServer invite.fromGameEvent 出错" + e.getLocalizedMessage());
        }
    }

    /** 邀请创角事件 */
    public static void dispatchInviteCreateEvent(GameBody game, Role invitee, String inviterRoleId) {
        dispatchInviteEvent(game, createInviteEvent(InviteEvent.CREATE, invitee, inviterRoleId));
    }

    /** 邀请登录事件 */
    public static void dispatchInviteLoginEvent(GameBody game, Role invitee, String inviterRoleId) {
        dispatchInviteEvent(game, createInviteEvent(InviteEvent.LOGIN, invitee, inviterRoleId));
    }

    /** 邀请升级事件 */
    public static void dispatchInviteLevelUpEvent(GameBody game, Role invitee, String inviterRoleId) {
        dispatchInviteEvent(game, createInviteEvent(InviteEvent.LEVEL_UP, invitee, inviterRoleId));
    }
}
